package cn.owen.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.mail.util.BASE64DecoderStream;
import com.sun.mail.util.BASE64EncoderStream;

public class DesEncryption {
	
	private static final Logger logger = LoggerFactory.getLogger(DesEncryption.class);

	private static Cipher ecipher;
	
	private static Cipher dcipher;

	private static final byte key[] = "xxxxx_is_weak_encryption@858".getBytes();
	
	public static String encrypt(String str) throws Exception{
		
        DESKeySpec desKeySpec = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey skey = keyFactory.generateSecret(desKeySpec);
		
		ecipher = Cipher.getInstance("DES");
		ecipher.init(Cipher.ENCRYPT_MODE, skey);
		
		byte[] utf8 = str.getBytes("UTF-8");

		byte[] enc = ecipher.doFinal(utf8);

		enc = BASE64EncoderStream.encode(enc);

		return new String(enc);
	}
	
	public static String decrypt(String str) throws Exception {
		logger.debug("*****str:"+str);
		
		DESKeySpec desKeySpec = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey skey = keyFactory.generateSecret(desKeySpec); 

		dcipher = Cipher.getInstance("DES");

		dcipher.init(Cipher.DECRYPT_MODE, skey);

		byte[] dec = BASE64DecoderStream.decode(str.getBytes());

		byte[] utf8 = dcipher.doFinal(dec);

		return new String(utf8, "UTF-8");
	}
	
	public static boolean isValid(String data, String expectedEmail, int validHour) throws Exception{
		
		String decryptedString = decrypt(data);
		
		logger.debug("*****decryptedString:"+decryptedString);
		
		String[] stringArray = decryptedString.split(java.util.regex.Pattern.quote("|"));
		
		String email = stringArray[0];		
		if(!email.equals(expectedEmail)){
			return false;
		}

		String dateTime = stringArray[1];
		SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy_HHmm");
		Date date = dateFormat.parse(dateTime);
		if(!isTimeValid(date,new Date(),validHour)){
			return false;
		}
		
		return true;
	}
	
	public static boolean isTimeValid(Date startDate, Date endDate, int validHour){
		long secs = (endDate.getTime() - startDate.getTime()) / 1000;
		int hours = (int) (secs / 3600);    
		return (hours<validHour);
	}
	
	
	public static void main(String args[]){
		try {
			String s1=  DesEncryption.encrypt("24");
			System.out.println("加密："+s1);
			String s2 = DesEncryption.decrypt("s1");
			System.out.println("解密："+s2);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*try {
			System.out.println(DesEncryption.decrypt("SIXEBeqXX+XuKZcqz50ZIvwrp2PMF3ktqsg1PwIIfN0UnNHzFpid4A=="));
		} catch (Exception e) {
			System.out.println(e.toString());
		}*/
	}
	
}
